package sorting.tests;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import sorting.programs.*;
import sorting.programs.proper.SortingMerge;
import wv.TestUtility;

public class SortingTestUtility implements TestUtility {
	
	public static <T extends Comparable<? super T>>
	boolean isSorted(Iterable<T> iterable) {
		Iterator<T> iter = iterable.iterator();
		if (!iter.hasNext()) {
			return true;
		}
		T t = iter.next();
		while (iter.hasNext()) {
			T t2 = iter.next();
			if (t.compareTo(t2) > 0) {
				return false;
			}
			t = t2;
		}
		return true;
	}
	
	public static boolean isPermutation(List<Integer> originalList1, List<Integer> originalList2) {
		List<Integer> list1 = new ArrayList<Integer>(originalList1);
		List<Integer> list2 = new ArrayList<Integer>(originalList2);
		if (list1.size() == 0)
			return (list2.size() == 0);
		else {
			int elem = (Integer) list1.get(0);
			if (list2.contains(elem)) {
				list1.remove(0);
				list2.remove(list2.lastIndexOf(elem));
				return isPermutation(list1, list2);
			}
			return false;
		}
	}

	public static Class<?> classToTest = SortingMerge.class;	

	public static <E> boolean correctFrequency(List<E> toCheck,
			List<E> comparison) {
		for (E i : toCheck) {
			if (frequency(i, toCheck) != frequency(i, comparison))
				return false;
		}
		return true;
	}

	private static <E> int frequency(E i, List<E> toCheck) {
		int num = 0;
		for (E x : toCheck)
			if (x.equals(i))
				num++;
		return num;
	}
	
	public static <E> boolean containsAll(List<E> list1, List<E> list2) {
		for (E el : list2)
			if (!list1.contains(el))
				return false;
		return true;
	}

	public static Sorting getObjectOfClassToTest() {
		try {
			return (Sorting) classToTest.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
		
	}

	@Override
	public void setClassToTest(Class<?> newClass) {
		classToTest = newClass;
		
	}
}
